package com.ybkj.o2o.zhuanche.common;

import java.util.Optional;
import java.util.Queue;
import java.util.Random;
import java.util.concurrent.ConcurrentLinkedQueue;

import com.ybkj.o2o.zhuanche.conf.ThriftServiceClient;
import com.ybkj.o2o.zhuanche.thrift.IdsResult;
import com.ybkj.o2o.zhuanche.thrift.ThriftService;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.stereotype.Component;

import static com.ybkj.o2o.zhuanche.conf.ZookeeperConfiguration.ServiceClients;

@Component
public class SerialNumber {

  private static final int GEN_NUM = 100;

  private static Queue<Long> idsQueue = new ConcurrentLinkedQueue<>();


  /**
   * 获取流水号.
   */

  public synchronized String getSeqNo() {


    if (CollectionUtils.isEmpty(idsQueue)) {

      //调用下
      Optional<ThriftServiceClient> option = ServiceClients.stream().findAny();

      try {

        if (option.isPresent()) {

          ThriftService.Client client = option.get().getClient();

          IdsResult idsResult = client.nextIds(Long.parseLong(option.get().getWorkerId()), GEN_NUM);

          idsQueue.addAll(idsResult.getIds());

        }

      } catch (Exception ex) {
        ex.printStackTrace();
        return random();
      }

    }


    if (idsQueue.size() <= 0) {
      return random();
    }
    return String.format("%d", idsQueue.remove());
  }


  private String random() {

    Random random = new Random();
    random.setSeed(System.currentTimeMillis());

    StringBuilder sb = new StringBuilder();

    for (int i = 0; i < 14; i++) {
      sb.append(random.nextInt(9));
    }

    return sb.toString();
  }

}
